/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        
        if(root == nullptr) return ;
        
        TreeNode* head = new TreeNode();
        TreeNode* tail = head;
        
        stack<TreeNode*> node_stack;
        node_stack.push(root);

        while(node_stack.size()){

            TreeNode* curr = node_stack.top();
            node_stack.pop();
            if(curr->right) node_stack.push(curr->right);
            if(curr->left) node_stack.push(curr->left);

            curr->left = nullptr;
            curr->right = nullptr;
            tail->right = curr;
            tail = tail->right;
        }

        return ;
    }
};